<?php
namespace app\shop\model;

use app\BaseModel;
use app\integral\model\Integral;
use app\member\model\DiscountGoods;
use think\facade\Db;
use app\shop\model\indexUserInfo;


class IndexCouponRecord extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_coupon_record';
    /**
     * @var array
     * 查询器
     */
    protected $append = [
        'limit_data_text',
        'user_info_text',
        'end_time_text',
        'user_text'

    ];
    /**
     * @param $value
     * 转时间
     */

    public function getEndTimeTextAttr($value,$data){

        if(isset($data['start_time'])&&isset($data['end_time'])){

            if($data['start_time']==0){
                $end_time = $data['end_time']-time();

                return lbGetDates($end_time);
            }else{

                return date('Y-m-d H:i:s',$data['start_time']).'~'.date('Y-m-d H:i:s',$data['end_time']);
            }

        }

    }
    /**
     * @param $value
     * @param $data
     * @return mixed
     * limit data
     */
    public function getLimitDataTextAttr($value,$data){
        if ($data['limit_type'] == 1 && !empty($data['limit_cate'])) {
            $limit_cate = explode(',', $data['limit_cate']);
            $limit_data = Db::name('longbing_card_shop_type')->where('id', 'in', $limit_cate)->column('title');
        } elseif ($data['limit_type'] == 2 && !empty($data['limit_goods'])) {
            $limit_goods = explode(',', $data['limit_goods']);
            $limit_data = Db::name('longbing_card_goods')->where('id', 'in', $limit_goods)->column('name');
        }
        return !empty($limit_data)?array_values($limit_data):['全部'];
    }
    /**
     * @param $value
     * @param $data
     * @return mixed
     * user info
     */
    public function getUserInfoTextAttr($value,$data){

        $user_info = Db::name('longbing_card_user_info')->where(['fans_id'=>$data['staff_id']])->field('id,fans_id,avatar,name')->find();

        $user_info['avatar'] = lbUserAvatar($data['staff_id']);

        $user_info['name']   = lbUserName($data['staff_id']);

        $user_info = !empty($user_info)?transImages($user_info,['avatar']):$user_info;
        return $user_info;



    }
    /**
     * @param $value
     * @param $data
     * @return mixed
     * user info
     */
    public function getUserTextAttr($value,$data){

        $user_info = Db::name('longbing_card_user')->where(['id'=>$data['user_id']])->field('avatarUrl,nickName,id')->find();

        $user_info['avatarUrl'] = !empty($user_info['avatarUrl'])?$user_info['avatarUrl']:'https://lbqnyv2.migugu.com/defaultAvatar.png';

        $user_info = !empty($user_info)?transImages($user_info,['avatarUrl']):$user_info;

        return $user_info;
    }
    /**
     * @param $dis
     * @param $page
     * @return array
     * @throws \think\exception\DbException
     * 获取我的优惠券列表
     */
    public function recordList($dis,$page=10){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;
    }

    /**
     * @param $dis
     * @param $data
     * @return IndexCouponRecord
     * 编辑我的优惠券
     */
    public function recordUpdate($dis,$data){
        $data['update_time'] = time();
        $res = $this->where($dis)->update($data);
        return $res;

    }

    /**
     *
     * 修改过期的优惠状态
     */

    public function endRecord(){

        $res = $this->where('status','=',1)->where('end_time','<',time())->update(['status'=>3]);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-08 16:45
     * @功能说明:添加优惠券
     */
    public function insertRecord($coupon,$order){
        //过期时间
        $end_time   = $coupon['end_time_type']==1?$coupon['end_time_day']*86400+time():$coupon['end_time'];
        //开始时间
        $start_time = $coupon['end_time_type']==1?0:$coupon['start_time'];

        $insert_data = array(

            'user_id'     => $order['user_id'],

            'staff_id'    => $order['staff_id'],

            'coupon_id'   => $coupon['id'],

            'title'       => $coupon['title'],

            'type'        => $coupon['type'],

            'full'        => $coupon['full'],

            'reduce'      => $coupon['reduce'],

            'end_time'    => $end_time,

            'uniacid'     => $coupon['uniacid'],

            'limit_type'  => $coupon['limit_type'],

            'company_limit'  => $coupon['company_limit'],

            'limit_cate'  => $coupon['limit_cate'],

            'limit_goods' => $coupon['limit_goods'],

            'activity_rules' => $coupon['activity_rules'],

            'start_time'  => $start_time,
            //优惠券类型
            'coupon_type' => $coupon['coupon_type'],
            //内容
            'content'     => $coupon['content'],

            'send_type'   => $coupon['send_type'],
        );

        Db::startTrans();

        $record_id = $this->recordAdd($insert_data);
        //如果限制了公司
        if($coupon['company_limit']==1){
            //公司模型
            $company_model  = new CompanyCoupon();

            $dis = [

                'coupon_id' => $coupon['id'],

                'type'      => 0

            ];
            //获取公司到id
            $company_id     = $company_model->where($dis)->column('company_id');
            //添加记录
            $company_model->companyCouponAdd($record_id,$company_id,$coupon['uniacid'],1);
        }

        Db::commit();

        return $record_id;

    }

    /**
     * @param $data
     * @return int|string
     * 领取福包
     */

    public function recordAdd($data){

        $data['create_time'] = time();

        $data['update_time'] = time();

        $res = $this->insert($data);

        $id  = $this->getLastInsID();

        return $id;
    }

    /**
     *
     *获取记录详情
     */
    public function recordInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():$data;
    }
    /**
     *
     *获取记录条数
     */
    public function recordCount($dis){
        $data = $this->where($dis)->count();
        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-16 10:21
     * @功能说明:查看单张优惠券可以抵扣的钱
     */
    public function discontPrice($goods_info,$coupon_id,$user_id){

        $item = $this->where(['id'=>$coupon_id])->find()->toArray();

        $all_price = 0;

        foreach ($goods_info as &$vs){

            $dis = array();

            if($item['limit_type']==1&&!empty($item['limit_cate'])){

                $limit_cate = explode(',',$item['limit_cate']);

                $dis[]      = ['type','in',$limit_cate];

                $dis[]      = ['id','=',$vs['goods_id']];

            }elseif($item['limit_type']==2&&!empty($item['limit_goods'])){

                $limit_goods= explode(',',$item['limit_goods']);

                $dis[]      = in_array($vs['goods_id'],$limit_goods)?['id','=',$vs['goods_id']]:['id','=','not id'];

            }else{

                $dis[]      = ['id','=',$vs['goods_id']];
            }

            $goods_model    = new IndexGoods();

            $is_goods_price = $goods_model->where($dis)->find();

            $goods_price    = 0;

            if(!empty($is_goods_price)){

                $spe_price_model = new IndexShopSpePrice();

                $goods_price = $spe_price_model->where(['id'=>$vs['spe_price_id']])->sum('price');
            }
            $discount_goods_model = new DiscountGoods();

            $discount_member = $discount_goods_model->userGoodsDiscount($vs['goods_id'],$user_id,$item['uniacid']);

            $all_price  +=$goods_price*$vs['number']*$discount_member;
        }

        return $all_price;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-08-03 16:18
     * @功能说明:检查订单
     */
    public function checkOrder($record_id,$input,$user_id,$order_insert,$goods_info){


        if(!empty($input['collage_id'])){

            return ['code'=>400,'msg'=>'拼团不能使用福包'];
        }

        $coupon_record_check = $this->recordInfo(['id'=>$record_id,'user_id'=>$user_id]);

        if ( !$coupon_record_check ) {

            return ['code'=>400,'msg'=>'未找到该福包领取记录'];

        }
        if ( $coupon_record_check[ 'type' ] != 1 ) {

            return ['code'=>400,'msg'=>'只有线下福包才能核销'];

        }
        if ( $coupon_record_check[ 'end_time' ] < time() ) {

            return ['code'=>400,'msg'=>'福包已过期'];

        }
        if ( $coupon_record_check[ 'status' ] != 1 ) {

            return ['code'=>400,'msg'=>'只有待使用的福包才能核销'];

        }
        if ($coupon_record_check['send_type'] ==0&&$coupon_record_check[ 'staff_id' ] != $input['staff_id'] ) {

            return ['code'=>400,'msg'=>'福包只能在领取的员工下才能使用'];

        }
        $order_insert[ 'record_id' ] = $record_id;
        //计算出可以折扣多少钱
        $discount_price = $this->discontPrice($goods_info,$record_id,$user_id);

        if ($order_insert['total_price'] >= $coupon_record_check[ 'full' ] ) {

            $coupon_record_check[ 'reduce' ] = $coupon_record_check[ 'reduce' ]>$discount_price?$discount_price:$coupon_record_check[ 'reduce' ];

            $order_insert['total_price']  = sprintf( '%.2f', $order_insert['total_price'] - $coupon_record_check[ 'reduce' ] );

            $order_insert['total_price']  = $order_insert['total_price']>0?$order_insert['total_price']:0;

            $order_insert['record_money'] = $coupon_record_check[ 'reduce' ];

            $record_res  = $this->recordUpdate(['user_id'=>$user_id,'id'=>$record_id],['status'=>2]);

            if($record_res===false){

                return ['code'=>400,'msg'=>'福包抵扣失败，请重新下单'];

            }
        }


        return $order_insert;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-08-03 16:18
     * @功能说明:检查订单
     */
    public function checkOrderV2($record_id,$input,$user_id,$order_insert,$goods_info){

        if(!empty($input['collage_id'])){

            return ['code'=>400,'msg'=>'拼团不能使用福包'];
        }

        $coupon_record_check = $this->recordInfo(['id'=>$record_id,'user_id'=>$user_id]);

        if ( !$coupon_record_check ) {

            return ['code'=>400,'msg'=>'未找到该福包领取记录'];

        }
        if ( $coupon_record_check[ 'type' ] != 1 ) {

            return ['code'=>400,'msg'=>'只有线下福包才能核销'];

        }
        if ( $coupon_record_check[ 'end_time' ] < time() ) {

            return ['code'=>400,'msg'=>'福包已过期'];

        }
        if ( $coupon_record_check[ 'status' ] != 1 ) {

            return ['code'=>400,'msg'=>'只有待使用的福包才能核销'];

        }
        if ($coupon_record_check['send_type'] ==0&&$coupon_record_check[ 'staff_id' ] != $input['staff_id'] ) {

            return ['code'=>400,'msg'=>'福包只能在领取的员工下才能使用'];

        }
        $order_insert[ 'record_id' ] = $record_id;

        $is_integral = !empty($input['is_integral'])?$input['is_integral']:0;
        //计算出可以折扣多少钱
        $discount_arr   = $this->discontPriceV2($goods_info,$record_id,$user_id,$is_integral);

        $discount_price = $discount_arr['discount_price'];

        if ($order_insert['price'] >= $coupon_record_check[ 'full' ] ) {

            $coupon_record_check[ 'reduce' ] = $coupon_record_check[ 'reduce' ]>$discount_price?$discount_price:$coupon_record_check[ 'reduce' ];

            $order_insert['total_price']  = sprintf( '%.2f', $order_insert['total_price'] - $coupon_record_check[ 'reduce' ] );

            $order_insert['total_price']  = $order_insert['total_price']>0?$order_insert['total_price']:0;

            $order_insert['record_money'] = $coupon_record_check['reduce'];

            $record_res  = $this->recordUpdate(['user_id'=>$user_id,'id'=>$record_id],['status'=>2]);

            if($record_res===false){

                return ['code'=>400,'msg'=>'福包抵扣失败，请重新下单'];

            }

            if(!empty($discount_arr['list'])){

                $order_goods_model = new IndexShopOrderGoods();

                $order_goods_id    = array_column($discount_arr['list'],'id');
                //总的实际支付家
                $pay_price = $order_goods_model->where('id','in',$order_goods_id)->sum('pay_price');

                if($pay_price>0){

                    foreach ($discount_arr['list'] as $vs){

                        $bin = $vs['pay_price']/$pay_price;

                        $singe_discount_price = $vs['pay_price'] - $bin*$coupon_record_check['reduce']>0?$vs['pay_price'] - $bin*$coupon_record_check['reduce']:0;
                        //修改子订单的实际支付价格
                        $order_goods_model->where(['id'=>$vs['id']])->update(['pay_price'=>$singe_discount_price]);
                    }

                }

            }

        }else{

            return ['code'=>400,'msg'=>'福包抵扣失败，请重新下单'];

        }

        return $order_insert;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-03 16:18
     * @功能说明:检查订单
     */
    public function checkCouponPrice($record_id,$user_id,$pay_price,$goods_info){

        $coupon_record_check = $this->recordInfo(['id'=>$record_id,'user_id'=>$user_id]);
        //计算出可以折扣多少钱
        $discount_arr   = $this->discontPriceV2($goods_info,$record_id,$user_id);

        $discount_price = $discount_arr['discount_price'];

        $reduce = 0;

        if ($pay_price >= $coupon_record_check[ 'full' ] ) {

            $reduce = $coupon_record_check[ 'reduce' ]>$discount_price?$discount_price:$coupon_record_check[ 'reduce' ];

            $reduce = $reduce>$pay_price?$pay_price:$reduce;

        }

        return $reduce;

    }




    /**
     * @author chenniang
     * @DataTime: 2020-09-16 10:21
     * @功能说明:查看单张优惠券可以抵扣的钱
     */
    public function discontPriceV2($goods_info,$coupon_id,$user_id,$is_integral=0){

        $item = $this->where(['id'=>$coupon_id])->find()->toArray();

        $all_price = $pay_price = 0;

        $list      = [];

        $integral_model = new Integral();

        foreach ($goods_info as &$vs){

            $dis = array();

            if($item['limit_type']==1&&!empty($item['limit_cate'])){

                $limit_cate = explode(',',$item['limit_cate']);

                $dis[]      = ['type','in',$limit_cate];

                $dis[]      = ['id','=',$vs['goods_id']];

            }elseif($item['limit_type']==2&&!empty($item['limit_goods'])){

                $limit_goods= explode(',',$item['limit_goods']);

                $dis[]      = in_array($vs['goods_id'],$limit_goods)?['id','=',$vs['goods_id']]:['id','=','not id'];

            }else{

                $dis[]      = ['id','=',$vs['goods_id']];
            }

            $goods_model    = new IndexGoods();

            $is_goods_price = $goods_model->where($dis)->find();

            $goods_price    = 0;
            //可以抵扣的商品
            if(!empty($is_goods_price)){

                $spe_price_model = new IndexShopSpePrice();

                $goods_price     = $spe_price_model->where(['id'=>$vs['spe_price_id']])->sum('price');
                //使用积分
                if($is_integral==1){

                    $integral_atv = $integral_model->atvIng($vs['goods_id'],$vs['spe_price_id'],1);

                    if(!empty($integral_atv)){

                        $goods_price = $integral_atv['price'];

                    }

                }

                $list[] = $vs;
            }

            $discount_goods_model = new DiscountGoods();

            $discount_member = $discount_goods_model->userGoodsDiscount($vs['goods_id'],$user_id,$item['uniacid']);

            $all_price  += $goods_price*$vs['number']*$discount_member;

        }

        $data['discount_price'] = round($all_price,2);

        $data['list']           = $list;

        return $data;

    }











}